RAG Workflow For Stock Earnings Report Analysis

工作流概述

这是一个包含18个节点的复杂工作流,主要用于自动化处理各种任务。

工作流源代码

下载
{
  "id": "fqaNojXWrspqjfkY",
  "meta": {
    "instanceId": "69133932b9ba8e1ef14816d0b63297bb44feb97c19f759b5d153ff6b0c59e18d"
  },
  "name": "RAG Workflow For Stock Earnings Report Analysis",
  "tags": [],
  "nodes": [
    {
      "id": "1a621f76-9636-430d-94dd-d5e7dcd5afdc",
      "name": "Pinecone Vector Store",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePinecone",
      "position": [
        380,
        -60
      ],
      "parameters": {
        "mode": "insert",
        "options": {},
        "pineconeIndex": {
          "__rl": true,
          "mode": "list",
          "value": "company-earnings",
          "cachedResultName": "company-earnings"
        }
      },
      "credentials": {
        "pineconeApi": {
          "id": "bQTNry52ypGLqt47",
          "name": "PineconeApi account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "e5936e45-0f58-48e9-9ab4-cc69f2ef6578",
      "name": "Embeddings Google Gemini",
      "type": "@n8n/n8n-nodes-langchain.embeddingsGoogleGemini",
      "position": [
        300,
        220
      ],
      "parameters": {
        "modelName": "models/text-embedding-004"
      },
      "credentials": {
        "googlePalmApi": {
          "id": "jLOqyTR4yTT1nYKi",
          "name": "Google Gemini(PaLM) Api account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "e98dbc8e-6b4a-415d-a044-85e590fcb105",
      "name": "Default Data Loader",
      "type": "@n8n/n8n-nodes-langchain.documentDefaultDataLoader",
      "position": [
        520,
        200
      ],
      "parameters": {
        "loader": "pdfLoader",
        "options": {},
        "dataType": "binary"
      },
      "typeVersion": 1
    },
    {
      "id": "ae77f5f4-3704-4b66-9c3f-27d6bd3f68c3",
      "name": "Recursive Character Text Splitter",
      "type": "@n8n/n8n-nodes-langchain.textSplitterRecursiveCharacterTextSplitter",
      "position": [
        560,
        380
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "d939c9db-0edc-4205-b8e5-fb34b0076510",
      "name": "Loop Over Items",
      "type": "n8n-nodes-base.splitInBatches",
      "position": [
        -120,
        -60
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "4f8421b4-1a11-4ac3-a9ca-1d725a8ec98e",
      "name": "When clicking ‘Test workflow’",
      "type": "n8n-nodes-base.manualTrigger",
      "position": [
        -360,
        640
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "c9e2ec39-c34d-4d8e-b772-d1c1cd823d9e",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -40,
        640
      ],
      "parameters": {
        "text": "Give me a report on Google's last 3 quarter earnings. Format it in markdown. Focus on the differences and trends. Spot any outliers.",
        "options": {
          "systemMessage": "You are a highly skilled financial analyst specializing in analyzing Google's (Alphabet Inc.) financial performance. You have access to two powerful tools:

1.  **Vector Store Tool:** This tool allows you to retrieve relevant information from the past three quarters of Google's earnings reports (PDF documents). The documents have been processed and stored as embeddings in a vector database, enabling semantic search. Use this tool to find specific information related to revenue, expenses, profits, losses, growth, key metrics, management commentary, and any other relevant financial data.
2.  **Google Docs Tool:** This tool allows you to create, edit, and format Google Docs. Use this tool to save your findings into a Google Doc.

Your task is to answer user queries related to Google's financial performance based on the last three quarters' earnings reports. When a user asks a question:

1.  **Understand the User's Intent:** Carefully analyze the user's query to determine what specific financial information they are seeking. Identify keywords, timeframes (e.g., \"previous quarter\"), and the type of analysis requested (e.g., trend analysis, comparison, explanation).
2.  **Retrieve Relevant Information:** Use the Vector Store Tool to search for and retrieve the most relevant text passages from the earnings reports that address the user's query. Retrieve multiple, diverse chunks to ensure comprehensive coverage.
3.  **Synthesize and Analyze:**  Analyze the information from the retrieved text chunks. Identify key trends, patterns, and insights related to the user's query.
4.  **Generate Report in Google Docs:** Use the Google Docs Tool to create a new Google Doc (or append to an existing one, if specified by the user). Structure the report with clear headings, bullet points, and concise paragraphs. Include the following in your report as appropriate:
    *   **Executive Summary:** A brief overview of the key findings.
    *   **Revenue Analysis:**  Report on revenue figures, growth rates, and key revenue drivers.
    *   **Expense Analysis:** Report on major expense categories and their impact on profitability.
    *   **Profitability Analysis:** Discuss net income, profit margins, and earnings per share (EPS).
    *   **Key Metrics:** Include other relevant financial metrics mentioned in the reports (e.g., operating income, cash flow, segment performance).
    *   **Management Commentary:** Summarize any relevant insights or explanations provided by Google's management in the earnings calls or reports.
    *   **Trend Analysis:** Compare the current quarter's performance to the previous two quarters, highlighting significant changes or trends.
    *   **Visualizations:** If possible, use the Google Docs tool to insert basic charts or tables to visually represent the data. (You might need to guide the user on how to do this if the tool has limitations.)
5.  **Cite Sources:**  Clearly indicate the source of your information (e.g., \"Q2 2023 Earnings Report\") for each data point or analysis.
6.  **Maintain a Professional Tone:** Write in a clear, concise, and objective tone, as expected of a financial analyst. Avoid speculation or making unsubstantiated claims.

Your ultimate goal is to provide the user with a well-structured, informative, and accurate financial report based on the data available in the last three quarters of Google's earnings reports.
Save the report in as a Google Doc using the available tool!"
        },
        "promptType": "define"
      },
      "typeVersion": 1.7
    },
    {
      "id": "40534b4d-3061-4054-8c0a-b08fe32deaf7",
      "name": "Vector Store Tool",
      "type": "@n8n/n8n-nodes-langchain.toolVectorStore",
      "position": [
        360,
        860
      ],
      "parameters": {
        "name": "company_financial_earnings_data_tool",
        "description": "Retrieve information about the last 3 quarters of Google Earnings"
      },
      "typeVersion": 1
    },
    {
      "id": "c584d5f6-1fac-420f-a28d-71f51b555e67",
      "name": "Google Gemini Chat Model1",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        620,
        1060
      ],
      "parameters": {
        "options": {},
        "modelName": "models/gemini-2.0-flash-exp"
      },
      "credentials": {
        "googlePalmApi": {
          "id": "jLOqyTR4yTT1nYKi",
          "name": "Google Gemini(PaLM) Api account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "f4f993d0-c80a-4f26-bc51-fe7df1012606",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        -160,
        860
      ],
      "parameters": {
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "id": "tQLWnWRzD8aebYvp",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "4aa3726e-a105-4bfe-b1df-06c3c9ece18a",
      "name": "Pinecone Vector Store (Retrieval)",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePinecone",
      "position": [
        260,
        1080
      ],
      "parameters": {
        "options": {},
        "pineconeIndex": {
          "__rl": true,
          "mode": "list",
          "value": "company-earnings",
          "cachedResultName": "company-earnings"
        }
      },
      "credentials": {
        "pineconeApi": {
          "id": "bQTNry52ypGLqt47",
          "name": "PineconeApi account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "e08dd92a-a7a1-4204-bef9-54611a2dee92",
      "name": "Save Report to Google Docs",
      "type": "n8n-nodes-base.googleDocs",
      "position": [
        460,
        640
      ],
      "parameters": {
        "actionsUi": {
          "actionFields": [
            {
              "text": "={{ $json.output }}",
              "action": "insert"
            }
          ]
        },
        "operation": "update",
        "documentURL": "1aOUl-mnCaI4__tULmBZSvWlOQhTHdD-RUPesP7_sFT4"
      },
      "credentials": {
        "googleDocsOAuth2Api": {
          "id": "nnE7RqZglLn8XarL",
          "name": "Google Docs account"
        }
      },
      "typeVersion": 2
    },
    {
      "id": "1984765a-3148-4bcf-9d20-fe29291fda6d",
      "name": "Embeddings Google Gemini (retrieval)",
      "type": "@n8n/n8n-nodes-langchain.embeddingsGoogleGemini",
      "position": [
        240,
        1260
      ],
      "parameters": {
        "modelName": "models/text-embedding-004"
      },
      "credentials": {
        "googlePalmApi": {
          "id": "jLOqyTR4yTT1nYKi",
          "name": "Google Gemini(PaLM) Api account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "9b0bff2e-06f4-4c89-b9dc-c54cfb79577c",
      "name": "List Of Files To Load (Google Sheets)",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        -380,
        -60
      ],
      "parameters": {
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": 1476836405,
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1ckP-ZgAMs2l2sFUpLAXx-gWNOQrHXoAs48Vo271X3rs/edit#gid=1476836405",
          "cachedResultName": "GOOG"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1ckP-ZgAMs2l2sFUpLAXx-gWNOQrHXoAs48Vo271X3rs",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1ckP-ZgAMs2l2sFUpLAXx-gWNOQrHXoAs48Vo271X3rs/edit?usp=drivesdk",
          "cachedResultName": "Watchlist"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "sRJmS2k8zdqVjtJL",
          "name": "Google Sheets account"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "b0d58ce5-9ac0-4f0f-ac7c-d6cb27551d82",
      "name": "Download File From Google Drive",
      "type": "n8n-nodes-base.googleDrive",
      "position": [
        160,
        -60
      ],
      "parameters": {
        "fileId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $('List Of Files To Load (Google Sheets)').item.json['File URL'] }}"
        },
        "options": {
          "fileName": "={{ $('List Of Files To Load (Google Sheets)').item.json['10Q'] }}"
        },
        "operation": "download"
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "uixLsi5TmrfwXPeB",
          "name": "Google Drive account"
        }
      },
      "typeVersion": 3
    },
    {
      "id": "28817b3d-fb54-4dc2-83bc-3ac27320712b",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1100,
        80
      ],
      "parameters": {
        "width": 500,
        "height": 740,
        "content": "## Set up steps
1. Google Cloud Project & Vertex AI API:
	* Create a Google Cloud project.
	* Enable the Vertex AI API for your project.
2. Google AI API key:
	* Obtain a Google AI API key from Google AI Studio.
3. Pinecone account and API key:
	* Create a free account on the Pinecone website.
	* Obtain your API key from your Pinecone dashboard.
	* Create an index named company-earnings in your Pinecone project.
4. Google Drive - download and save financial documents:
	* Go to a company you want to analize and download their quarterly earnings PDFs
	* Save the PDFs in Google Drive
	* Create a Google Sheet that stores a list of file URLs pointing to the PDFs you downloaded and saved to Google Drive
5. Configure credentials in your n8n environment for:
	* Google Sheets OAuth2
	* Google Drive OAuth2
	* Google Docs OAuth2
	* Google Gemini(PaLM) Api (using your Google AI API key)
	* Pinecone API (using your Pinecone API key)
6. Import and configure the workflow:
	* Import this workflow into your n8n instance.
	* Update the List Of Files To Load (Google Sheets) node to point to your Google Sheet.
	* Update the Download File From Google Drive to point to the column where the file URLs are
	* Update the Save Report to Google Docs node to point to your Google Doc where you want the report saved."
      },
      "typeVersion": 1
    },
    {
      "id": "eecb1c25-c019-44e4-b254-a919f80faee7",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        380,
        -260
      ],
      "parameters": {
        "content": "## Loading data to Pinecone vector store"
      },
      "typeVersion": 1
    },
    {
      "id": "8371f7f8-29a7-4711-b635-d5538f3441b8",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -40,
        460
      ],
      "parameters": {
        "content": "## AI Agent Report Generation using RAG"
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "pinData": {
    "AI Agent": [
      {
        "json": {
          "output": "# Google (Alphabet Inc.) Financial Report: Last 3 Quarters

## Executive Summary
Google has demonstrated solid revenue growth across the last three quarters, although there are notable fluctuations in operating income, net income, and other income/expense categories. While revenue from both Google Services and Cloud shows consistent year-over-year growth, the operating margins have shown variability. 

## Revenue Analysis
- **Quarter 1:**
  - **Revenue:** $80.5 billion, a 15% year-over-year increase.
  - **Google Services Revenue:** Up $8.4 billion (14%).
  - **Google Cloud Revenue:** Up $2.1 billion (28%).

- **Quarter 2:**
  - **Revenue:** $84.7 billion, a 14% year-over-year increase.
  - **Google Services Revenue:** Up $7.6 billion (12%).
  - **Google Cloud Revenue:** Up $2.3 billion (29%).

- **Quarter 3:**
  - **Revenue:** $88.3 billion, a 15% year-over-year increase.
  - **Google Services Revenue:** Up $8.5 billion (13%).
  - **Google Cloud Revenue:** Up $2.9 billion (35%).

### Key Trends
- Consistent revenue growth across all three quarters.
- Strong growth in Google Cloud, indicating it is a significant area of expansion.

## Expense Analysis
- **Cost of Revenue:**
  - **Quarter 1:** $33.7 billion (up 10% year-over-year).
  - Reason for increase: Higher total acquisition costs, content acquisition costs, and depreciation.

- **Operating Income:**
  - **Quarter 1:** $17.415 billion (25% operating margin).
  - **Quarter 2:** $21.838 billion (29% operating margin).
  - **Quarter 3:** $21.343 billion (28% operating margin).

### Observations
- Operating margins have fluctuated, while overall costs have continued to rise.
  
## Profitability Analysis
- **Net Income:**
  - **Quarter 1:** $15.051 billion.
  - **Quarter 2:** $18.368 billion.
  - **Quarter 3:** $19.689 billion.
  
- **Diluted EPS:**
  - **Quarter 1:** $1.17.
  - **Quarter 2:** $1.44.
  - **Quarter 3:** $1.55.

### Summary
While net income has increased, the fluctuations in other income and expense metrics have affected profitability.

## Key Metrics
- **Operating Margins:**
  - Q1: 25%
  - Q2: 29%
  - Q3: 28%

- **Other Income (Expense), Net:**
  - Q1: $790 million.
  - Q2: $65 million.
  - Q3: -$146 million. (Downturn to a negative number)

## Management Commentary
Management has pointed out that increased revenue performance in Google Cloud is encouraging, especially given the challenges in the overall economic environment.

## Trend Analysis
- **Comparative Performance:**
  - Revenue trends show consistency, ranging from 14%-15% growth year-over-year.
  - Operating income showed a decreasing trend from Q1 ($17.415 billion) to Q2 ($21.838 billion) and slightly decreased again in Q3 ($21.343 billion).
  
### Noteworthy Observations
- **Outliers:**
  - Significant volatility in other income/expense net, transitioning from $790 million in Q1 to a loss of $146 million in Q3.
  
- **Operating Margins:** 
  - Variability seen in margins from Q1 (25%) to Q2 (29%) and back down to Q3 (28%) shows a trend of volatility.

## Conclusion
Google has maintained a strong financial position characterized by solid revenue growth. However, the apparent volatility in other income/expense and operating margins warrants closer scrutiny, as it could impact future profitability. The continuous growth in Google Cloud is a positive indicator and suggests strong potential for the coming quarters.

---

This report provides a comprehensive overview of Google's financial performance over the past three quarters, highlighting key metrics, trends, and outliers. If you require further details or specific analysis, please let me know!"
        }
      }
    ]
  },
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "30c9a6f0-8ace-40c3-8ca7-a79fd91c12a7",
  "connections": {
    "AI Agent": {
      "main": [
        [
          {
            "node": "Save Report to Google Docs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [],
        [
          {
            "node": "Download File From Google Drive",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Vector Store Tool": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Default Data Loader": {
      "ai_document": [
        [
          {
            "node": "Pinecone Vector Store",
            "type": "ai_document",
            "index": 0
          }
        ]
      ]
    },
    "Pinecone Vector Store": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings Google Gemini": {
      "ai_embedding": [
        [
          {
            "node": "Pinecone Vector Store",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Google Gemini Chat Model1": {
      "ai_languageModel": [
        [
          {
            "node": "Vector Store Tool",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Download File From Google Drive": {
      "main": [
        [
          {
            "node": "Pinecone Vector Store",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pinecone Vector Store (Retrieval)": {
      "ai_vectorStore": [
        [
          {
            "node": "Vector Store Tool",
            "type": "ai_vectorStore",
            "index": 0
          }
        ]
      ]
    },
    "Recursive Character Text Splitter": {
      "ai_textSplitter": [
        [
          {
            "node": "Default Data Loader",
            "type": "ai_textSplitter",
            "index": 0
          }
        ]
      ]
    },
    "When clicking ‘Test workflow’": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings Google Gemini (retrieval)": {
      "ai_embedding": [
        [
          {
            "node": "Pinecone Vector Store (Retrieval)",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "List Of Files To Load (Google Sheets)": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}

功能特点

  • 自动检测新邮件
  • AI智能内容分析
  • 自定义分类规则
  • 批量处理能力
  • 详细的处理日志

技术分析

节点类型及作用

  • @N8N/N8N Nodes Langchain.Vectorstorepinecone
  • @N8N/N8N Nodes Langchain.Embeddingsgooglegemini
  • @N8N/N8N Nodes Langchain.Documentdefaultdataloader
  • @N8N/N8N Nodes Langchain.Textsplitterrecursivecharactertextsplitter
  • Splitinbatches

复杂度评估

配置难度:
★★★★☆
维护难度:
★★☆☆☆
扩展性:
★★★★☆

实施指南

前置条件

  • 有效的Gmail账户
  • n8n平台访问权限
  • Google API凭证
  • AI分类服务订阅

配置步骤

  1. 在n8n中导入工作流JSON文件
  2. 配置Gmail节点的认证信息
  3. 设置AI分类器的API密钥
  4. 自定义分类规则和标签映射
  5. 测试工作流执行
  6. 配置定时触发器(可选)

关键参数

参数名称 默认值 说明
maxEmails 50 单次处理的最大邮件数量
confidenceThreshold 0.8 分类置信度阈值
autoLabel true 是否自动添加标签

最佳实践

优化建议

  • 定期更新AI分类模型以提高准确性
  • 根据邮件量调整处理批次大小
  • 设置合理的分类置信度阈值
  • 定期清理过期的分类规则

安全注意事项

  • 妥善保管API密钥和认证信息
  • 限制工作流的访问权限
  • 定期审查处理日志
  • 启用双因素认证保护Gmail账户

性能优化

  • 使用增量处理减少重复工作
  • 缓存频繁访问的数据
  • 并行处理多个邮件分类任务
  • 监控系统资源使用情况

故障排除

常见问题

邮件未被正确分类

检查AI分类器的置信度阈值设置,适当降低阈值或更新训练数据。

Gmail认证失败

确认Google API凭证有效且具有正确的权限范围,重新进行OAuth授权。

调试技巧

  • 启用详细日志记录查看每个步骤的执行情况
  • 使用测试邮件验证分类逻辑
  • 检查网络连接和API服务状态
  • 逐步执行工作流定位问题节点

错误处理

工作流包含以下错误处理机制:

  • 网络超时自动重试(最多3次)
  • API错误记录和告警
  • 处理失败邮件的隔离机制
  • 异常情况下的回滚操作